package com.fuqi.android.zhongcai.business.dinuan.view.activity;


import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.fuqi.android.zhongcai.R;
import com.fuqi.android.zhongcai.application.UniApplication;
import com.fuqi.android.zhongcai.base.Constants;
import com.fuqi.android.zhongcai.base.model.ProvinceList;
import com.fuqi.android.zhongcai.base.request.api.GetClientApi;
import com.fuqi.android.zhongcai.base.request.api.GetStaffApi;
import com.fuqi.android.zhongcai.base.request.result.GetStaffResult;
import com.fuqi.android.zhongcai.base.view.activity.BaseActivity;
import com.fuqi.android.zhongcai.base.view.widget.wheelwidget.OptionsPickerView;
import com.fuqi.android.zhongcai.base.view.widget.wheelwidget.TimePickerView;
import com.fuqi.android.zhongcai.business.shuig.OrderDict;
import com.fuqi.android.zhongcai.business.shuig.request.api.CreateOrderApi;
import com.fuqi.android.zhongcai.business.shuig.request.result.CreateOrderResult;
import com.fuqi.android.zhongcai.business.shuig.view.activity.ShuiGActivity;
import com.fuqi.android.zhongcai.business.shuig.view.widget.CJRow.ARResponse;
import com.fuqi.android.zhongcai.sql.Dic;
import com.fuqi.android.zhongcai.sql.dao.SQLDao;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.DateUtil;
import com.fuqi.android.zhongcai.utils.LogUtils;
import com.fuqi.android.zhongcai.utils.RegexUtil;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.fuqi.framework.utils.StringUtil;
import com.fuqi.framework.utils.SystemUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.fuqi.android.zhongcai.base.Constants.TYPE_DI_NUAN;


public class DiNuanMarkOrderActivity extends BaseActivity {

    @Bind(R.id.tv_kehu)
    TextView tvKeHu;
    @Bind(R.id.tv_jxs)
    TextView tvJXS;
    @Bind(R.id.et_sales_name)
    EditText etSales;
    @Bind(R.id.et_yezhu_name)
    EditText etYezhu;
    @Bind(R.id.et_yezhu_tel)
    EditText etYezhuTel;
    @Bind(R.id.tv_wei_count)
    TextView tvWeiCount;
    @Bind(R.id.tv_chu_count)
    TextView tvChuCount;
    @Bind(R.id.tv_yangtai_count)
    TextView tvYangTaiCount;
    @Bind(R.id.tv_anzhuang_content)
    TextView tvInstallContent;
    @Bind(R.id.tv_anzhuang_date)
    TextView tvInstallDate;
    @Bind(R.id.tv_product)
    TextView tvProduct;
    @Bind(R.id.tv_pay_way)
    TextView tvPayWay;
    @Bind(R.id.tv_diqu)
    TextView tvAdress;
    @Bind(R.id.et_contact_name)
    EditText etContactName;
    @Bind(R.id.et_contact_phone)
    EditText etContactPhone;
    @Bind(R.id.et_detail)
    EditText etDetail;
    @Bind(R.id.et_remark)
    EditText etRemark;

    private ArrayList<Dic> options1Items = new ArrayList<>();
    private ArrayList<GetStaffResult> options2Items = new ArrayList<GetStaffResult>(); // 客户
    private ArrayList<GetStaffResult> options3Items = new ArrayList<GetStaffResult>(); // 经销商
    OptionsPickerView pvOptions;

    OptionsPickerView pvOptionsProvince;
    TimePickerView pvTime;

    final int TYPE_SELECT_CHU = 0;
    final int TYPE_SELECT_WEI = 1;
    final int TYPE_SELECT_YANG_TAI = 2;
    final int TYPE_SELECT_INSTALL_CONTENT = 3;
    final int TYPE_SELECT_INSTALL_DATE = 4;
    final int TYPE_SELECT_PRODUCT = 5;
    final int TYPE_SELECT_PAY_WAY = 6;
    final int TYPE_SELECT_JXS = 7;
    final int TYPE_SELECT_KEHU = 8;

    String roleType = "1";
    ARResponse response;

    @OnClick({R.id.tv_jxs,R.id.tv_kehu,R.id.btn_submit,R.id.tv_diqu,R.id.rl_address,R.id.tv_wei_count,R.id.tv_chu_count,R.id.tv_yangtai_count,R.id.tv_anzhuang_content,R.id.rl_anzhuang_content,R.id.tv_product,R.id.rl_product,R.id.tv_pay_way,R.id.rl_pay_way,R.id.tv_anzhuang_date})
    public void onClick(View view){

        switch(view.getId()){
            case R.id.tv_anzhuang_date:
                SystemUtil.hideSystemKeyboad(this);
                pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
                pvTime.setTime(new Date());
                pvTime.setCyclic(false);
                pvTime.setCancelable(true);
                //时间选择后回调
                pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

                    @Override
                    public void onTimeSelect(Date date) {
                        String sDate = DateUtil.getStringByFormat(date,DateUtil.dateFormatYMD);
                        tvInstallDate.setText(sDate);
                    }
                });
                pvTime.show();
                break;
            case R.id.btn_submit:

                String houseType = tvChuCount.getText().toString().trim() + "厨" + tvWeiCount.getText().toString().trim() + "卫" + tvYangTaiCount.getText().toString().trim() + "阳台";
                if(paramsIsValid()) {
                    RequestManager.getInstance().call(new CreateOrderApi(new CreateOrderApi.CreateOrderParams(roleType,
                            tvKeHu.getTag().toString(),tvJXS.getTag().toString(),  etSales.getText().toString().trim(),
                            etYezhu.getText().toString().trim(),etYezhuTel.getText().toString().trim(),Constants.TYPE_DI_NUAN,
                            etContactName.getText().toString().trim(), etContactPhone.getText().toString().trim(), houseType,
                            tvInstallContent.getTag().toString().trim(), tvInstallDate.getText().toString().trim(),
                            tvAdress.getText().toString().trim(), etDetail.getText().toString().trim(),
                            tvProduct.getTag().toString().trim(), tvPayWay.getTag().toString().trim(),
                            etRemark.getText().toString().trim(), UniApplication.getInstance().getUserInfo().getUserid()),
                            respMakeOrderListener, errorListener));

                }

                break;
            case R.id.tv_jxs:
                if(StringUtil.isEmpty(tvKeHu.getText().toString())) {
                    ActivityUtils.toast("请先选择报单来源。");
                    return;
                }
                SystemUtil.hideSystemKeyboad(this);
                selectByWheelWidget(TYPE_SELECT_JXS);

                break;
            case R.id.tv_kehu:
                SystemUtil.hideSystemKeyboad(this);
                selectByWheelWidget(TYPE_SELECT_KEHU);

                break;
            case R.id.tv_wei_count:

                SystemUtil.hideSystemKeyboad(this);
                selectByWheelWidget(TYPE_SELECT_WEI);

                break;
            case R.id.tv_chu_count:

                SystemUtil.hideSystemKeyboad(this);
                selectByWheelWidget(TYPE_SELECT_CHU);

                break;
            case R.id.tv_yangtai_count:
                SystemUtil.hideSystemKeyboad(this);

                selectByWheelWidget(TYPE_SELECT_YANG_TAI);

                break;
            case R.id.tv_anzhuang_content:
            case R.id.rl_anzhuang_content:

                SystemUtil.hideSystemKeyboad(this);
                selectByWheelWidget(TYPE_SELECT_INSTALL_CONTENT);

                break;

            case R.id.tv_product:
            case R.id.rl_product:
                SystemUtil.hideSystemKeyboad(this);
                selectByWheelWidget(TYPE_SELECT_PRODUCT);

                break;

            case R.id.tv_pay_way:
            case R.id.rl_pay_way:
                SystemUtil.hideSystemKeyboad(this);
                selectByWheelWidget(TYPE_SELECT_PAY_WAY);

                break;

            case R.id.tv_diqu:
            case R.id.rl_address:
                SystemUtil.hideSystemKeyboad(this);

                pvOptionsProvince.setPicker(ProvinceList.getOptions1Items(), ProvinceList.getOptions2Items(), ProvinceList.getOptions3Items(), true);
                pvOptionsProvince.setCyclic(false, false, false);
                pvOptionsProvince.setSelectOptions(1, 1, 1);
                pvOptionsProvince.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        //返回的分别是三个级别的选中位置
                        String tx = ProvinceList.getOptions1Items().get(options1).getPickerViewText()
                                + ProvinceList.getOptions2Items().get(options1).get(option2)
                                + ProvinceList.getOptions3Items().get(options1).get(option2).get(options3).getPickerViewText();
                        tvAdress.setText(tx);
                    }
                });
                pvOptionsProvince.show();


                break;

        }


    }


    private void selectByWheelWidget(final int selectType){
        switch (selectType){
            case TYPE_SELECT_KEHU:

                pvOptions = new OptionsPickerView(this);
                pvOptions.setPicker(options2Items);
                pvOptions.setCyclic(false);
                pvOptions.show();
                pvOptions.setSelectOptions(1, 0, 0);
                pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        if(options2Items.size() <= options1)       return ;
                        options3Items.clear();
                        tvJXS.setText("");
                        tvJXS.setTag("");
                        tvKeHu.setText(options2Items.get(options1).getName());
                        tvKeHu.setTag(options2Items.get(options1).getUserId());
                        //ActivityUtils.toast("options1: " + options1);
                        LogUtils.i("juner select position: " + options1);
                        RequestManager.getInstance().call(new GetClientApi(new GetClientApi.GetClientParams(options2Items.get(options1).getUserId()),
                                respJXSListener, errorListener));
                    }
                });
                return;
            case TYPE_SELECT_JXS:

                pvOptions = new OptionsPickerView(this);
                pvOptions.setPicker(options3Items);
                pvOptions.setCyclic(false);
                pvOptions.show();
                pvOptions.setSelectOptions(1, 0, 0);
                pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        if(options3Items.size() <= options1)       return ;
                        tvJXS.setText(options3Items.get(options1).getName());
                        tvJXS.setTag(options3Items.get(options1).getUserattachId());
                        //ActivityUtils.toast("options1: " + options1);
                        LogUtils.i("juner select position: " + options1);

                    }
                });
                return;

            case TYPE_SELECT_CHU:
            case TYPE_SELECT_WEI:
            case TYPE_SELECT_YANG_TAI:
                options1Items.clear();
                options1Items.add(new Dic("一","一"));
                options1Items.add(new Dic("二","二"));
                options1Items.add(new Dic("三","三"));
                options1Items.add(new Dic("四","四"));
                options1Items.add(new Dic("五","五"));
                options1Items.add(new Dic("六","六"));
                options1Items.add(new Dic("七","七"));
                break;

            case TYPE_SELECT_INSTALL_CONTENT:



                options1Items.clear();
                List<Dic> dics = SQLDao.getInstance(getApplicationContext()).selectDNSY(OrderDict.DNSYType.SJ_AZNR);
                /*options1Items.add("安装");
                options1Items.add("改装");
                options1Items.add("加装");
                options1Items.add("返工");
                options1Items.add("检修");
                options1Items.add("空跑");*/
                options1Items.addAll(dics);

                break;

            case TYPE_SELECT_PRODUCT:

                options1Items.clear();
                dics = SQLDao.getInstance(getApplicationContext()).selectDNSY(TYPE_DI_NUAN);
                /*options1Items.add("A套餐");
                options1Items.add("B套餐");
                options1Items.add("C套餐");
                options1Items.add("D套餐");*/
                options1Items.addAll(dics);


                break;

            case TYPE_SELECT_PAY_WAY:

                options1Items.clear();
                dics = SQLDao.getInstance(getApplicationContext()).selectDNSY(OrderDict.DNSYType.SJ_SKFS);
                /*options1Items.add("现场收取");
                options1Items.add("代收");
                options1Items.add("月结");*/
                options1Items.addAll(dics);

                break;
        }

        pvOptions.setPicker(options1Items);
        pvOptions.setCyclic(false);
        pvOptions.show();
        pvOptions.setSelectOptions(1, 0, 0);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                if(options1Items.size() <= options1)       return ;
                switch (selectType){

                    case TYPE_SELECT_CHU:
                        tvChuCount.setText(options1Items.get(options1).toString());
                        break;
                    case TYPE_SELECT_WEI:
                        tvWeiCount.setText(options1Items.get(options1).toString());
                        break;
                    case TYPE_SELECT_YANG_TAI:
                        tvYangTaiCount.setText(options1Items.get(options1).toString());
                        break;

                    case TYPE_SELECT_INSTALL_CONTENT:
                        tvInstallContent.setText(options1Items.get(options1).toString());
                        tvInstallContent.setTag(options1Items.get(options1).getPbianma());
                        break;

                    case TYPE_SELECT_PRODUCT:
                        tvProduct.setText(options1Items.get(options1).toString());
                        tvProduct.setTag(options1Items.get(options1).getId());
                        break;

                    case TYPE_SELECT_PAY_WAY:
                        tvPayWay.setText(options1Items.get(options1).toString());
                        tvPayWay.setTag(options1Items.get(options1).getPbianma());
                        break;
                }


                //ActivityUtils.toast("options1: " + options1);
                LogUtils.i("juner select position: " + options1);

            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(pvOptions.isShowing()){
                pvOptions.dismiss();
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void initView() {
        pvOptions = new OptionsPickerView(this);
        pvOptionsProvince = new OptionsPickerView(this);

        if (UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_GRKH)){
            // 用户
            roleType = "1";
//            rlKeHu.setVisibility(View.GONE);
            tvKeHu.setText(UniApplication.getInstance().getUserInfo().getName());
            tvKeHu.setTag(UniApplication.getInstance().getUserInfo().getUserid());
            tvKeHu.setEnabled(false);
            tvKeHu.setClickable(false);
            tvJXS.setEnabled(true);
            RequestManager.getInstance().call(new GetClientApi(new GetClientApi.GetClientParams(UniApplication.getInstance().getUserInfo().getUserid()),
                    respJXSListener, errorListener));

        }else if(UniApplication.getInstance().getCurrentRole().equals(Constants.ROLE_NQ)){
            roleType = "2";
            RequestManager.getInstance().call(new GetStaffApi(new GetStaffApi.GetStaffParams(Constants.ROLE_GRKH,Constants.TYPE_DI_NUAN),
                    respClientListener, errorListener));
        }
    }

    @Override
    public void initListener() {
    }

    @Override
    public void initData() {
        titleBar.setTitle("立即下单");
        if(getIntent().hasExtra("response")){
            response = new ARResponse(getIntent().getStringExtra("response"));
        }
        if(response != null){
            etSales.setText(response.getValue("SALSE_NAME"));
            etYezhu.setText(response.getValue("OWNER_NAME"));
            etYezhuTel.setText(response.getValue("OWNER_PHONE"));
            etContactName.setText(response.getValue("CONTACT_NAME"));
            etContactPhone.setText(response.getValue("CONTACT_PHONE"));
            etDetail.setText(response.getValue("ADDR_DETAIL"));
            etRemark.setText(response.getValue("REMARK"));
            tvInstallDate.setText(response.getValue("INSTALL_DATE"));
            tvAdress.setText(response.getValue("ADDR_AREA"));
        }
    }

    private boolean paramsIsValid() {

        if(!RegexUtil.checkNotNull(tvKeHu.getText().toString())){

            ActivityUtils.toast("请选择报单来源");
            return false;

        }else if(!RegexUtil.checkNotNull(tvJXS.getText().toString())){

            ActivityUtils.toast("请选择客户");
            return false;

        }else if(!RegexUtil.checkNotNull(etSales.getText().toString())){

            ActivityUtils.toast("请输入业务员");
            return false;

        }else if(!RegexUtil.checkNotNull(etYezhu.getText().toString())){

            ActivityUtils.toast("请输入业主姓名");
            return false;

        }else if(!RegexUtil.checkNotNull(etYezhuTel.getText().toString())){

            ActivityUtils.toast("请输入业主电话");
            return false;

        }else if(!RegexUtil.checkNotNull(etContactName.getText().toString())){

            ActivityUtils.toast("请输入项目经理");
            return false;

        } else if(!RegexUtil.checkNotNull(etContactPhone.getText().toString())){
            ActivityUtils.toast("请输入项目经理手机号");
            return false;

        } else if(!RegexUtil.checkNotNull(tvInstallContent.getText().toString())){
            ActivityUtils.toast("请选择安装内容");
            return false;

        }else if(!RegexUtil.checkNotNull(tvAdress.getText().toString())){
            ActivityUtils.toast("请选择地址");
            return false;

        }

        else if(!RegexUtil.checkNotNull(tvInstallDate.getText().toString())){
            ActivityUtils.toast("请选择安装日期");
            return false;

        }else if(!RegexUtil.checkDate(tvInstallDate.getText().toString().trim())){
            ActivityUtils.toast("安装日期必须大于当前日期");
            return false;
        }else if(!RegexUtil.checkDateWithMakeOrder(tvInstallDate.getText().toString().trim())){
            ActivityUtils.toast("当天报单，安装日期从第二天开始。如果晚于17：30的报单，则无法选择第二天的日期，日期从后天开始");
            return false;
        }

        else if(!RegexUtil.checkNotNull(etDetail.getText().toString())){
            ActivityUtils.toast("请输入详细地址");
            return false;

        }else if(!RegexUtil.checkNotNull(tvProduct.getText().toString())){
            ActivityUtils.toast("请选择套餐类型");
            return false;

        }else if(!RegexUtil.checkNotNull(tvPayWay.getText().toString())){
            ActivityUtils.toast("请选择支付方式");
            return false;

        }else{

            return true;

        }
    }
    Response.Listener<GetStaffResult[]> respJXSListener = new Response.Listener<GetStaffResult[]>() {

        @Override
        public void onResponse(GetStaffResult[] response) {
            if (HandleCode.requestSuccess()) {
                if (response != null && response.length > 0){
                    options3Items.clear();
                    Collections.addAll(options3Items, response);
                }
                Log.i("juner", "juner respListener response : ");
            } else {

            }
        }
    };

    Response.Listener<GetStaffResult[]> respClientListener = new Response.Listener<GetStaffResult[]>() {

        @Override
        public void onResponse(GetStaffResult[] response) {
            if (HandleCode.requestSuccess()) {
                if (response != null && response.length > 0){
                    options2Items.clear();
                    Collections.addAll(options2Items, response);
                }
                Log.i("juner", "juner respListener response : ");
            } else {

            }
        }
    };


    Response.Listener<CreateOrderResult> respMakeOrderListener = new Response.Listener<CreateOrderResult>() {

        @Override
        public void onResponse(CreateOrderResult response) {

            if (HandleCode.requestSuccess()) {
                Bundle bundle = new Bundle();
                bundle.putString("order_id",response.getOrderId());
                bundle.putString("order_type",Constants.TYPE_DI_NUAN);
                if(true) {
                    ActivityUtils.startActivity(DiNuanMarkOrderActivity.this,ShuiGActivity.class,bundle);
                }

                finish();
                Log.i("juner", "juner response makeorder success! : ");
            } else {

                ActivityUtils.toast("下单失败");

            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            Log.i("juner", "juner  error.getMessage(): " + error.getMessage());

        }
    };

    @Override
    public boolean hasTitleBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_di_nuan;
    }
}
